import CryptoJS from 'crypto-js'


function padZero(num, targetLength = 2) {
  let str = `${num}`
  while (str.length < targetLength) {
    str = `0${str}`
  }
  return str
}

export function isMobile() {
  // 判断是否是移动设备的正则表达式
  const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;

  // 获取用户代理字符串
  const userAgent = navigator.userAgent;

  // 使用正则表达式进行匹配
  return mobileRegex.test(userAgent);
}

const SECOND = 1000
const MINUTE = 60 * SECOND
const HOUR = 60 * MINUTE
const DAY = 24 * HOUR

export function parseTimeData(time) {
  const days = Math.floor(time / DAY)
  const hours = Math.floor((time % DAY) / HOUR)
  const minutes = Math.floor((time % HOUR) / MINUTE)
  const seconds = Math.floor((time % MINUTE) / SECOND)
  const milliseconds = Math.floor(time % SECOND)
  return {
    days,
    hours,
    minutes,
    seconds,
    milliseconds
  }
}

export function parseFormat(format, timeData) {
  let {days, hours, minutes, seconds, milliseconds} = timeData
  // 如果格式化字符串中不存在DD(天)，则将天的时间转为小时中去
  if (format.indexOf('DD') === -1) {
    hours += days * 24
  } else {
    // 对天补0
    format = format.replace('DD', padZero(days))
  }
  // 其他同理于DD的格式化处理方式
  if (format.indexOf('HH') === -1) {
    minutes += hours * 60
  } else {
    format = format.replace('HH', padZero(hours))
  }
  if (format.indexOf('mm') === -1) {
    seconds += minutes * 60
  } else {
    format = format.replace('mm', padZero(minutes))
  }
  if (format.indexOf('ss') === -1) {
    milliseconds += seconds * 1000
  } else {
    format = format.replace('ss', padZero(seconds))
  }
  return format.replace('SSS', padZero(milliseconds, 3))
}

export function replaceSearchKeyword(result, keyword) {
  const Reg = new RegExp(keyword, 'ig')
  let res = ''
  if (result) {
    res = result.replace(Reg, `<span style="color: #507DAF;">$&</span>`)
    return res
  }
  return result
}

export function copyToClip(text) {
  return new Promise((resolve, reject) => {
    try {
      const input = document.createElement('textarea')
      input.value = text
      input.setAttribute('readonly', 'readonly')
      document.body.appendChild(input)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        document.body.removeChild(input)
        resolve(text)
      }
    } catch (error) {
      reject(error)
    }
  })
}

function randomString() {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const charactersLength = characters.length
  for (let i = 0; i < 32; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}

export function signfn(url, appKey = '25b9ecf1d0151ef1bc77325688d4aabc', key = 'abcf0a6290e385f4cbc67984be19c501') {
  const authTs = new Date().getTime()
  const authOnce = randomString()
  const authSign = CryptoJS.MD5(`act=${url}&app_key=${appKey}&nonce=${authOnce}&ts=${authTs}&key=${key}`)
      .toString()
  return {
    'auth-ts': authTs,
    'auth-nonce': authOnce,
    'auth-sign': authSign,
    'auth-key': appKey,
    'auth-type-id': 1
  }
}

export function getImageUrl(name) {
  return new URL(`../assets/images/${name}`, import.meta.url).href
}

export function sleep(delay = 1000) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, delay)
  })
}

/**
 * 树形结构转数组结构
 * @param {Array} array
 * @param {Array} newArray
 * @return newArray 新数组
 * */
export function treeToArray(array, newArray = []) {
  array.forEach(item => {
    newArray.push(item)
    if (item.children) {
      const {children} = item
      delete item.children
      treeToArray(children, newArray)
    }
  })
  return newArray
}

// dfs
export function findNodeById(data, name) {
  // 辅助函数，递归搜索节点
  function search(nodes, name) {
    for (const node of nodes) {
      if (node.name === name) {
        return node; // 找到节点，返回节点对象
      }
      if (node.children) {
        const result = search(node.children, name); // 递归搜索子节点
        if (result) {
          return result; // 如果找到了，直接返回结果
        }
      }
    }
    return null; // 如果未找到节点，返回 null
  }

  // 在整个数据中查找
  for (const item of data) {
    const result = search([item], name); // 从顶层节点开始搜索
    if (result) {
      return result; // 如果找到了，直接返回结果
    }
  }

  return null; // 如果未找到节点，返回 null
}

export function downloadBase64Image(base64Data, fileName) {
  // 创建一个链接元素
  const link = document.createElement('a');

  // 设置链接的 href 为 Base64 数据
  link.href = base64Data;

  // 设置下载的文件名
  link.download = fileName;

  // 将链接添加到文档中（在 Firefox 下需要这样做）
  document.body.appendChild(link);

  // 模拟点击链接以触发下载
  link.click();

  // 下载完成后移除链接
  document.body.removeChild(link);
}
